// pages/percentage/percentage.js
// import Toast from 'vant-weapp/toast/toast';
const app = getApp();
Page({
  data: {
    totalback:'0.00',
    sbStandard:[''],
    sbRate:['0%','10%','10.2%','10.5%','10.6%'],
    sbDaBingYL:[3],
    //个人缴纳比例的选择序号
    index1:[2],
    checkbox:[1],
    calDate:"",
    endDate:['结束时间'],
    startDate:['开始时间'],
    nowYear:""
  },

  /**
 * 
 * @param {String} dateStr1 
 * @param {String} dateStr2 
 */
compareDate:function(dateStr1,dateStr2){
  const date1 = new Date(dateStr1);
  const date2 = new Date(dateStr2);
  if (date1 > date2) {
      return 1;
  } else if (date1 < date2) {
      return 2;
  } else {
      return 0;
  }
},

/**
 * 
 * @param {String} startStr 
 * @param {String} endStr 
 */
calRentMonth:function(startStr,endStr){
  var end = endStr;
  var start = startStr;
  var cal = this.data.calDate;
  var result = 0;
  //传入其他字符串，直接返回0
  if(end.indexOf("-") === -1 || start.indexOf("-") === -1){
    return 0;
  }
  var startComCal = this.compareDate(cal,start);
  var calComEnd = this.compareDate(cal,end);
  // start <= cal < end
  if(startComCal <= 1 && calComEnd === 2){
     if(start.slice(0,4) !== cal.slice(0,4)){
      result = Number(cal.slice(-2));
     }else{
      result = Number(cal.slice(-2)) - Number(start.slice(-2)) + 1;
     }
     return result;
    // end 小于等于 cal的情况
  }else if(calComEnd <= 1)
  {
    // end跨年，只能是往前面算
    if(end.slice(0,4) !== cal.slice(0,4)){
      result = 0;
    }
    // end不跨年
    else{
      // start跨年
      if(start.slice(0,4) !== cal.slice(0,4)){
         result = Number(end.slice(-2));
      }
      // start不跨年
      else{
        result = Number(end.slice(-2)) - Number(start.slice(-2)) + 1;
      }
    }
     return result;
  }
  else{
     result = 0;
  }
  return result;
},

calSheBaoCount(){
  var sbStandard = this.data.sbStandard;
  var index1 = this.data.index1;
  var sbRate = this.data.sbRate;
  var sbDaBingYL = this.data.sbDaBingYL;
  var start = this.data.startDate;
  var end = this.data.endDate;
  var result = 0,rateTemp = 0,num = 0,months = 0;
  var head = '',tail = '',tagT = '1900-01',tagH = '1900-01'; 
  for(var i = 0;i < sbStandard.length;i++){
    if(start[i].indexOf("-") === -1 || end[i].indexOf("-") === -1){
      return -1.0;
    }
    months = this.calRentMonth(start[i],end[i])
    if(months === 0){
      // 时间跨年的话，直接不算跳过。
      continue;
    }
    else{
      num = index1[i];
      tail = end[i],head = start[i];
      rateTemp = Number(sbRate[num].slice(0,-1));
      if((this.compareDate(tail,tagH) === 2 || this.compareDate(tagT,head) === 2) && sbStandard[i] != ''){
        result = result + (rateTemp * Number(sbStandard[i]) / 100  + sbDaBingYL[i]) * months;
      }else{
        //有时间区间重复，直接返回-1，提示用户重新填写。
        return -1.0
      }
    }
    tagH = start[i],tagT = end[i];
  }
  result = result.toFixed(2);
  this.setData({totalback:result});
  return result;
},
  


  insert(e){
    var cb = this.data.checkbox;
    var start = this.data.startDate;
    var end = this.data.endDate;
    var sbYiliao = this.data.sbDaBingYL;
    var sbStandard = this.data.sbStandard;
    var index1 = this.data.index1;
    start.push('开始时间');
    cb.push(cb.length+1);
    end.push('结束时间');
    sbYiliao.push(3);
    sbStandard.push('');
    index1.push(2);
    this.setData({startDate:start,endDate:end,checkbox:cb,sbDaBingYL:sbYiliao,sbStandard:sbStandard,index1:index1});
  },

  delBind(e){
    var cb = this.data.checkbox;
    var start = this.data.startDate;
    var end = this.data.endDate; 
    var sbYiliao = this.data.sbDaBingYL;
    var sbStandard = this.data.sbStandard;
    var index1 = this.data.index1;
    start.pop();
    cb.pop();
    end.pop();
    sbYiliao.pop();
    sbStandard.pop();
    index1.pop();
    this.setData({startDate:start,endDate:end,checkbox:cb,sbDaBingYL:sbYiliao,sbStandard:sbStandard,index1:index1});
  },

  bindStartDateChange(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var start = this.data.startDate;
    start[nowIdx] = value;
    this.setData({startDate:start});
  },

  bindEndDateChange(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var start = this.data.startDate;
    if(start[nowIdx].indexOf("-") === -1){
      wx.showToast({
        title: '请先输入开始时间！',
        icon:'none'
      });
      return;
    }
    var end = this.data.endDate;
    end[nowIdx] = value;
    this.setData({endDate:end});
  },
  
  onSecurateCount(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var sbStandardArray = this.data.sbStandard
    if(/^(0|[1-9][0-9]*)$/.test(value) || /^([1-9][0-9]*\.)$/.test(value) || /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/.test(value)){
      sbStandardArray[nowIdx] = value;
      this.setData({sbStandard:sbStandardArray});
      // this.calSheBaoCount();
      return;
    }else{
       wx.showToast({
         title: '请正确输入社保缴纳基数！\r\n(仅数字，最多2位小数)',
         icon:'none'
       });
       //胡写就清空！
       sbStandardArray[nowIdx] = '';
       this.setData({sbStandard:sbStandardArray});
    }
    return;
  },
  bindPickerSbRate: function(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    var nowIdx=e.currentTarget.dataset.idx;
    var index1 = this.data.index1;
    index1[nowIdx] = e.detail.value
    this.setData({index1:index1});
    // console.log(e.detail.value)
    // this.calSheBaoCount();
  },

  onDaBingChange(event){
    var nowIdx=event.currentTarget.dataset.idx;
    var sbDaBingYL = this.data.sbDaBingYL;
    console.log(event.detail);
    console.log(nowIdx);
    sbDaBingYL[nowIdx] = Number(event.detail)
    this.setData({sbDaBingYL:sbDaBingYL});
    console.log(sbDaBingYL);
    // this.calSheBaoCount();
  },

  btn(e){
    wx.showModal({
      title: '社保个人缴纳比例说明',
      showCancel:false,
      content: '大部分地区个人承担养老8%，个人承担医疗2%，个人承担失业0.2%，个人交三险，企业交五险，因此默认是10.2%，也可根据不同地域政策进行选择。',
    });
    return false;
  },
  
  /**
   * sbStandard:[''],
    sbRate:['0%','10%','10.2%','10.5%','10.6%'],
    sbDaBingYL:[3],
    //个人缴纳比例的选择序号
    index1:[2],
    checkbox:[1],
    calDate:"",
    endDate:['结束时间'],
    startDate:['开始时间'],
   */
  onCompute(){
    const that = this;
    var val = that.calSheBaoCount();

    // app.globalData.sbDaBingYL = that.data.sbDaBingYL;
    // app.globalData.sbStandard = that.data.sbStandard;
    // app.globalData.sbIndex = that.data.index1;
    // app.globalData.sbEndDate = that.data.endDate;
    // app.globalData.sbStartDate = that.data.startDate;

    if(val < 0){
      wx.showToast({
        title: '请正确填写！\r\n1.时间区间不能有重合\r\n2.有未完整的内容',
        icon:'none',
        duration: 3000
      });
      return;
    }
    const sbStandard = JSON.stringify(that.data.sbStandard);
    const sbDaBingYL = JSON.stringify(that.data.sbDaBingYL);
    const index1 = JSON.stringify(that.data.index1);
    const checkbox = JSON.stringify(that.data.checkbox);
    const endDate = JSON.stringify(that.data.endDate);
    const startDate = JSON.stringify(that.data.startDate);
    wx.setStorageSync('sbStandard',sbStandard);
    wx.setStorageSync('sbDaBingYL',sbDaBingYL);
    wx.setStorageSync('sbIndex',index1);
    wx.setStorageSync('sbCheckbox',checkbox);
    wx.setStorageSync('sbEndDate',endDate);
    wx.setStorageSync('sbStartDate',startDate);
    var value = that.data.totalback;
    wx.showToast({
      title: '计算成功！',
      icon: 'sucess',
      duration: 2000,
      success: (res)=> {
        setTimeout(function() {
          let pages = getCurrentPages();//当前页面
          let prevPage = pages[pages.length - 2 ];
          prevPage.setData({
            securate:value,
            // secondSecurity:that.data.sbStandard,
            // secindGjj:that.data.gjjStandard
          });
          wx.navigateBack({
            delta: 1 
          })
        }, 2000);
      }
  });
  },
  formReset:function(){
    this.setData({
    totalback:'0.00',
    sbStandard:[''],
    sbDaBingYL:[3],
    index1:[2],
    checkbox:[1],
    endDate:['结束时间'],
    startDate:['开始时间'],
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */

  drawLine() {
    var context = wx.createCanvasContext('firstCanvas');
    context.setLineDash([5, 8],5);
    context.lineWidth = 10;
    context.strokeStyle = '#666';
    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(1040, 0);
    context.stroke();
    context.draw();
  },
  drawLine1() {
    var context = wx.createCanvasContext('secondCanvas');
    context.setLineDash([5, 8]);
    context.lineWidth = 10;
    context.strokeStyle = '#666';
    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(1040, 0);
    context.stroke();
    context.draw();
  },

  onLoad(options) {
    const mon = options.calDate;
    this.setData({calDate:mon});
    console.log(mon);
    const year = mon.split("-")
    this.setData({nowYear:year[0]});
    this.drawLine();
    this.drawLine1();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    // 页面显示前获取之前保存在本地的填写记录
    var value = wx.getStorageSync('sbStandard');
    if(value){
      that.setData({sbStandard:JSON.parse(value)});
    }
    value = wx.getStorageSync('sbDaBingYL');
    if(value){
      that.setData({sbDaBingYL:JSON.parse(value)});
    }
    value = wx.getStorageSync('sbIndex');
    if(value){
      that.setData({index1:JSON.parse(value)});
    }
    value = wx.getStorageSync('sbCheckbox');
    if(value){
      that.setData({checkbox:JSON.parse(value)});
    }
    value = wx.getStorageSync('sbEndDate');
    if(value){
      that.setData({endDate:JSON.parse(value)});
    }
    value = wx.getStorageSync('sbStartDate');
    if(value){
      that.setData({startDate:JSON.parse(value)});
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})